//
//  FirstViewController.m
//  tableViewLazyDemo
//
//  Created by kingboyrang on 2021/11/20.
//  Copyright © 2021 wulanzhou. All rights reserved.
//

#import "FirstViewController.h"
#import "ImageDownloader.h"
#import "ImageRecord.h"

@interface FirstViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray <ImageRecord *> *dataList; //数据源
@property (nonatomic,strong) NSMutableDictionary *tasksDic; //存储下载任务
@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.tasksDic = [NSMutableDictionary dictionaryWithCapacity:0];
    // Do any additional setup after loading the view.
    
    /**
     
     实现原理:
     
      tableView加载可见的cell图片(手指未拖动和减速动画快结束才加载)
     
     （1）绑定cell时，判断手指未拖动和减速动画快结束,才加载图片
         if (!tableView.dragging && !tableView.decelerating) {
            //加载图片
         }
     (2)tableview停止滚动，开始加载图像
        - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
            //加载图片
        }
     (3)tableView停止拖拽，没有减速动画
        - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
           //加载图片
        }
     (4)退出界面时，取消任务下载
     
     */
  
}

- (NSArray *)dataList{
    if (!_dataList) {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        for (int i=0; i< 100; i++) {
            
            ImageRecord *item = [[ImageRecord alloc] init];
            item.title = [NSString stringWithFormat:@"row %ld",(long)i];
            item.urlStr = @"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F12033458434%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639991799&t=59ff8c42bc3bc0f42119a43235d6418d";
            [array addObject:item];
        }
        _dataList = array;
    }
    return _dataList;
}

#pragma mark - 私有方法
//加载可见cell图片
- (void)showVisibleCellImage {
    NSArray *visibleCellArray = [self.tableView indexPathsForVisibleRows];
    for (NSIndexPath *indexPath in visibleCellArray) {
         [self downloadImage:indexPath];
    }
}

//下载图片
- (void)downloadImage:(NSIndexPath *)indexPath{
    
    ImageRecord *record = self.dataList[indexPath.row];
    
    ImageDownloader *downloader = self.tasksDic[indexPath];
    if (downloader == nil) {
        downloader = [[ImageDownloader alloc] initWithUrlStr:record.urlStr];
        //添加执行任务
        self.tasksDic[indexPath] = downloader;
    }
    __weak typeof(self) wself = self;
    [downloader setCompletionHandler:^(UIImage * _Nullable image) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
           if (image) {
               
             //1.压缩图片(对于图片过大处理)
             //UIImage *compressData=[FileUtils compressImage:image toByte:500];
               
             //2.等比缩放图片
             //UIImage *scaleImage=[FileUtils imageFitSizeScale:compressData targetSize:CGSizeMake(60, 60)];
               
              UITableViewCell *cell = [wself.tableView cellForRowAtIndexPath:indexPath];
              cell.imageView.image = image;

              //缓存图片
              record.image = image;
           }
           //移除完成的任务
           [wself.tasksDic removeObjectForKey:indexPath];
        });
    }];
    [downloader start];
}

#pragma mark - table source & delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
    }
    ImageRecord *record = self.dataList[indexPath.row];
    if (record.image) {
       cell.imageView.image = record.image;
    }else{
        cell.imageView.image = [UIImage imageNamed:@"head"];
        //手指未拖动和减速动画快结束
        if (!tableView.dragging && !tableView.decelerating) {
            //加载图片
            [self downloadImage:indexPath];
        }
    }
    cell.textLabel.text = record.title;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

#pragma mark - UIScrollView deletate
//当拖动后手指离开，这个时候是有减速动画的，当减速动画快结束的时候，意思味着将要停止滚动了，这个时候显示当前屏幕的cell图片
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //如果tableview停止滚动，开始加载图像
    [self showVisibleCellImage];
}
//这里的decelerate代表是否有减速动画，因为这里我需要实现的是没有减速动画的情况
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //tableView停止拖拽，停止滚动
    if (!decelerate) {
        [self showVisibleCellImage];
    }
}

#pragma mark - 界面消失时，取消网络请求
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    NSArray *values = self.tasksDic.allValues;
    [values makeObjectsPerformSelector:@selector(cancel)];
}



@end
